import Uploader from 'packages/BaseUpload/uploader';
const MAX_SIZE = 50 * 1024 * 1024
import EventBus from '@src/util/eventBus'
import { customerServiceSendNewMessage } from '@src/modules/im/imChat/components/messageBox/send.js'
import i18n from '@src/locales'

export default {
  name: 'file-mixin',
  data() {
    return {
    }
  },
  methods: {
    validate(file) {
      let fileName = file.name
      // 验证文件大小
      if (file.size > MAX_SIZE) return this.$t('common.base.uploadModal.fileSizeLowerTips', {size:'50m'})
      // 验证是否有扩展名
      let lastDotIndex = fileName.lastIndexOf('.')
      if (lastDotIndex < 0) return this.$t('common.base.uploadModal.unkonowFileType')
    },

    async handleFileChange(event, messageType) {
      let files = event.target.files
      if (files.length > 9) {
        return this.$message.error(this.$t('common.base.uploadModal.uploadCountTips', {count:9}))
      }
      if (files.length == 0) return
      let count = 0
      let loading = this.$loading()
      try {
        for (let i = 0; i < files.length; i++) {
          let file = files[i]
          let message = this.validate(file)
          if (message) {
            event.preventDefault()
            loading.close()
            return this.$message.error(message)
          }
          const { data } = await Uploader.upload(file, '/files/upload')
          const params = {
            conversationId:this.hxIdObj.conversationId,
            messageType,
            messageContent:{
              type:'custom',
              customEvent:messageType,
              customExts:{
                file_length:data.size,
                filename:data.fileName,
                url:data.ossUrl,
                fileId:data.id
              }
            }
          }
          let messageInfo = await customerServiceSendNewMessage(params)
          EventBus.$emit('addFileMessage', messageInfo);
          count++
          if (count >= files.length) loading.close()
        }
      } catch (error) {
        console.error('error', error);
        loading.close()
      }
    },
  },

}